#include "clock.h"
#include "ui_clock.h"
#include <QTime>
#include <QTimer>

Clock::Clock(QWidget *parent) :
    QWidget(parent), ui(new Ui::Clock)
{
    ui->setupUi(this);

    // 设置初始时间
//    QTime time = QTime::currentTime();
//    hour_ = time.hour();
//    minute_ = time.minute();
//    ui->hour1->setText(QString::number(hour_ / 10));
//    ui->hour2->setText(QString::number(hour_ % 10));
//    ui->minute1->setText(QString::number(minute_ / 10));
//    ui->minute2->setText(QString::number(minute_ % 10));

//    int remaining_time = (60 - time.second()) * 1000 - time.msec();

    // 每隔一秒刷新时钟的计时器
    timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, [this]()
    {
        QTime time = QTime::currentTime();
        int hour = time.hour();
        if (hour != hour_)
        {
            hour_ = hour;
            ui->hour1->setText(QString::number(hour_ / 10));
            ui->hour2->setText(QString::number(hour_ % 10));
        }

        int minute = time.minute();
        if (minute != minute_)
        {
            minute_ = minute;
            ui->minute1->setText(QString::number(minute_ / 10));
            ui->minute2->setText(QString::number(minute_ % 10));
        }

//        if (check_time())
//            minute_up();
    });
    timer->start(1000);

    // 把当前分钟剩余的毫秒计时完的计时器
//    timer_remain = new QTimer(this);
//    connect(timer_remain, &QTimer::timeout, this, [this]()
//    {
//        timer->start(60000);
//        minute_up();
//        timer_remain->stop();
//        timer_remain->deleteLater();
//    });
//    timer_remain->start(remaining_time);
}

void Clock::set_height(int h)
{
    QFont f = QFont("Microsoft YaHei", (h - 6) / 2);
    resize(h * 1.8, h);
    ui->hour1->setFont(f);
    ui->hour2->setFont(f);
    ui->label_3->setFont(f);
    ui->minute1->setFont(f);
    ui->minute2->setFont(f);
}

void Clock::minute_up()
{
    if (minute_ == 59)
    {
        minute_ = 0;
        if (hour_ == 23)
        {
            hour_ = 0;
        }
        else
        {
            ++hour_;
        }
    }
    else
    {
        ++minute_;
    }

    ui->hour1->setText(QString::number(hour_ / 10));
    ui->hour2->setText(QString::number(hour_ % 10));
    ui->minute1->setText(QString::number(minute_ / 10));
    ui->minute2->setText(QString::number(minute_ % 10));
}

bool Clock::check_time()
{
    QTime time = QTime::currentTime();
    int h = time.hour();
    int m = time.minute();

    // 如果时间有误差了
    if (h != hour_ || abs(m - minute_) > 1)
    {
        hour_ = h;
        minute_ = m;
        int remaining_time = (60 - time.second()) * 1000 - time.msec();
        timer->stop();
        timer_remain->stop();
        timer_remain->start(remaining_time);
        return false;
    }
    else
    {
        return true;
    }
}

Clock::~Clock()
{
    delete ui;
}
